package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.coyote.Request;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@SuppressWarnings("ALL")
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpServletRequest request;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * 1.从页面提交过来的数据比较少,所以用EmployeeDTO接收
     * 2.但表里的数据比较多,他的对应表是Employee
     * 3.需要考虑把EmployeeDTO转换成Employee
     * 4.不能强转,只能属性一个一个搬运
     * @param EmployeeDTO
     */
    public void add(EmployeeDTO employeeDTO) {
        // 创建employee对象
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置账号的状态，默认正常状态 1表示正常 0表示锁定
        employee.setStatus(1);
        //设置密码，默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置当前记录的创建时间和修改时间
        // mployee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());
        // // 获取令牌
        // String token = request.getHeader("token");
        // // 解析令牌
        // Claims claims = JwtUtil.parseJWT("itcast", token);  // 密钥+令牌
        // // 获取登录的id值
        // Integer id = (Integer) claims.get(JwtClaimsConstant.EMP_ID);
        //设置当前记录创建人id和修改人id
        // employee.setCreateUser(BaseContext.getCurrentId());// 创建人
        // employee.setUpdateUser(BaseContext.getCurrentId());// 更新人
        employeeMapper.add(employee);
    }

    /**
     * 员工分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page p = employeeMapper.page(dto);
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 员工启用和禁用
     * @param status
     * @param id
     */
    @Override
    public void updateStart(Integer status, Long id) {
        // Employee employee = new Employee();
        // employee.setStatus(status);
        // employee.setId(id);
        Employee employee = Employee.builder().status(status).id(id).build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id获取员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee  employee = employeeMapper.findById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工信息
     *
     * @param dto
     */
    @Override
    public void upate(EmployeeDTO dto) {
        // 创建员工对象Employee
        Employee employee = new Employee();
        // 搬运数据
        BeanUtils.copyProperties(dto,employee);
        // 补充数据
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

}
